package com.xianggu.mybatis.mapper;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

public class MyBatisXmlParser {
    /**
     * 使用 DOM 解析 XML
     * @param args
     */
    public static void main(String[] args) {
        try {
            // 加载 XML 文件
            File xmlFile = new File("D:\\javaDemo\\xiangGu\\xiangGu\\Springboot-xiangGu\\src\\main\\java\\com\\xianggu\\demo\\mapper\\xml\\UserMapper.xml");
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(xmlFile);

            // 获取根节点
            Element root = document.getDocumentElement();
            System.out.println("Root element: " + root.getNodeName());

            // 获取所有 SQL 语句
            NodeList nodeList = root.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    String sqlId = element.getAttribute("id");
                    String sql = element.getTextContent().trim();
                    System.out.println("SQL ID: " + sqlId);
                    System.out.println("SQL: " + sql);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}